package main
import (
	"net"
	"os"
	list "container/list"
	"strings"
)
const (
	_STR_CAP int = 1
	_PORT int = 12345
	_CONNS_CAP int = 20
	_MSGS_CAP int = 200
)
var (
	conns *list.List = list.New().Init()
	msgs *list.List = list.New().Init()
	ta net.TCPAddr
	l *net.TCPListener
	conn *net.TCPConn
	e error
)

func connHandler(c *net.TCPConn) {
	if c == nil {
		return
	}
	var writeBuf []byte = make([]byte,_STR_CAP)
	var tmsg,msg string
	for{
		if c == nil {
			return
		}
		n,e := c.Read(writeBuf)
		if e != nil {
			println("A person has leave!")
			c.Close()
			return
		}
		if n > 0 {
			tmsg = string(writeBuf)
			msg = strings.Trim(tmsg,string([]byte{0}))
			writeBuf = make([]byte,_STR_CAP)
		}
		switch msg {
			case "@quit":
				c.Close();return
			case "@get":
				println("@get")
				sendMsg(c)
			default :
				println(msg)
				println(".")
				addMsg(msg)
		}
	}
}

func sendMsg(c *net.TCPConn){
	el := msgs.Front()
	for{
		tmsg := el.Value.(string)
		c.Write([]byte(tmsg))
		el = el.Next()
		if el == nil {
			break
		}
	}
}

func addMsg(str string) {
	stradd := str + "\n"
	if msgs.Len() > _MSGS_CAP {
		msgs.Remove(msgs.Back())
	}
	msgs.PushFront(stradd)
}

func main(){

	ta = net.TCPAddr{net.IPv4(127,0,0,1),_PORT}
	l,e = net.ListenTCP("tcp4",&ta)
	if e != nil {
		println("Sorry,server cant start!")
		println(e)
		os.Exit(-1)
	}
	for{
		conn,e = l.AcceptTCP()
		println(conns.Len())
		if e == nil && conns.Len() < _CONNS_CAP {
			println("There is a new conn!")
			go connHandler(conn)
		}
	}
}
